package com.qyhl.webtv.module_news.luckydraw.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.qinanyu.bannerview.holder.SimpleHolder;
import com.qinanyu.bannerview.holder.SimpleHolderCreator;
import com.qinanyu.bannerview.listener.OnItemClickListener;
import com.qinanyu.bannerview.view.SimpleBannerView;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.LoadingDialog;
import com.qyhl.webtv.basiclib.utils.dialog.OtherDialog;
import com.qyhl.webtv.basiclib.utils.glide.GlideRoundTransform;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.live.TeleTextBean;
import com.qyhl.webtv.commonlib.entity.news.GlobalNewsBean;
import com.qyhl.webtv.commonlib.entity.news.LuckDrawInfoBean;
import com.qyhl.webtv.commonlib.entity.news.LuckDrawLiveBean;
import com.qyhl.webtv.commonlib.entity.news.LuckDrawPhaseBean;
import com.qyhl.webtv.commonlib.entity.news.NewsBean;
import com.qyhl.webtv.commonlib.utils.ItemSkipUtils;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.inter.HomeActivityInterface;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.module_news.utils.CashierInputFilter;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.weavey.loading.lib.LoadingLayout;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import cn.qqtheme.framework.picker.DatePicker;
import cn.qqtheme.framework.util.ConvertUtils;
import es.dmoral.toasty.Toasty;

/**
 * Created by Administrator on 2018/6/8.
 */

public class LuckDrawFragment extends BaseFragment implements LuckDrawFragmentContract.LuckDrawView, View.OnLayoutChangeListener {
    @BindView(R2.id.banner)
    SimpleBannerView banner;
    @BindView(R2.id.phase)
    TextView phase;
    @BindView(R2.id.invoice_scan)
    TextView invoiceScan;
    @BindView(R2.id.invoice_code)
    EditText invoiceCode;
    @BindView(R2.id.invoice_num)
    EditText invoiceNum;
    @BindView(R2.id.invoice_sum)
    EditText invoiceSum;
    @BindView(R2.id.invoice_datetime)
    TextView invoiceDatetime;
    @BindView(R2.id.invoice_phone)
    EditText invoicePhone;
    @BindView(R2.id.reset)
    TextView reset;
    @BindView(R2.id.commit)
    TextView commit;
    @BindView(R2.id.query_phone)
    EditText queryPhone;
    @BindView(R2.id.query_commit)
    TextView queryCommit;
    @BindView(R2.id.live_title)
    TextView liveTitle;
    @BindView(R2.id.live_cover)
    ImageView liveCover;
    @BindView(R2.id.live_tag)
    TextView liveTag;
    @BindView(R2.id.scan_num)
    TextView scanNum;
    @BindView(R2.id.luckdraw_live_layout)
    LinearLayout luckdrawLiveLayout;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.divider_line)
    View dividerLine;
    @BindView(R2.id.invoice_layout)
    LinearLayout invoiceLayout;
    @BindView(R2.id.invoice_business)
    EditText invoiceBusiness;
    @BindView(R2.id.complain)
    ImageView complain;
    @BindView(R2.id.invocie_empty_tv)
    TextView invocieEmptyTv;
    @BindView(R2.id.query_tickets_phone)
    EditText queryTicketsPhone;
    @BindView(R2.id.query_tickets_commit)
    TextView queryTicketsCommit;
    @BindView(R2.id.business_layout)
    LinearLayout businessLayout;
    @BindView(R2.id.business_divider)
    View businessDivider;
    @BindView(R2.id.my_tickets_layout)
    LinearLayout ticketsLayout;


    private LuckDrawFragmentPresenter mPresenter;

    private List<NewsBean> bannerList;

    private String sections;

    private String catalogId;

    private TeleTextBean mBean;

    private LoadingDialog.Builder builder;

    private String mYear, mMonth, mDay;

    private final int SCAN_CODE = 200;

    private boolean isHome;

    //屏幕高度
    public int screenHeight = 0;
    //软件盘弹起后所占高度阀值
    private int keyHeight = 0;

    private double moneyLimit = 0;

    public void setSections(String sections) {
        this.sections = sections;
    }

    public void setCatalogId(String catalogId) {
        this.catalogId = catalogId;
    }

    public void setHome(boolean home) {
        isHome = home;
    }

    HomeActivityInterface homeActivityInterface;

    public void setHomeActivityInterface(HomeActivityInterface homeActivityInterface) {
        this.homeActivityInterface = homeActivityInterface;
    }

    public static LuckDrawFragment newInstance(String sections, String catalogId, boolean isHome, HomeActivityInterface homeActivityInterface) {
        LuckDrawFragment fragment = new LuckDrawFragment();
        fragment.setSections(sections);
        fragment.setCatalogId(catalogId);
        fragment.setHome(isHome);
        fragment.setHomeActivityInterface(homeActivityInterface);
        return fragment;
    }


    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.news_fragment_luck_draw, null);
    }

    @Override
    protected void create() {
        mPresenter = new LuckDrawFragmentPresenter(this);
        //获取屏幕高度
        Point size = new Point();
        getActivity().getWindowManager().getDefaultDisplay().getSize(size);
        screenHeight = size.x;
        //阀值设置为屏幕高度的1/3
        keyHeight = screenHeight / 3;
        initView();
    }

    @Override
    protected void setListener() {
        setListeners();
        mPresenter.getPhase();
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    /**
     * 初始化
     */
    private void initView() {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.addOnLayoutChangeListener(this);
        if (StringUtils.isEmpty(sections)) {
            banner.setVisibility(View.GONE);
            dividerLine.setVisibility(View.GONE);
        } else {
            mPresenter.getTop(sections);
        }
        InputFilter[] filters = {new CashierInputFilter()};
        invoiceSum.setFilters(filters);

        if (CommonUtils.getInstance().getSite() == 181) {
            businessLayout.setVisibility(View.VISIBLE);
            businessDivider.setVisibility(View.VISIBLE);
            complain.setVisibility(View.VISIBLE);

            ticketsLayout.setVisibility(View.GONE);
        } else {
            businessLayout.setVisibility(View.GONE);
            businessDivider.setVisibility(View.GONE);
            complain.setVisibility(View.GONE);
            ticketsLayout.setVisibility(View.VISIBLE);
        }

        if (isHome) {
            mPresenter.getLive(catalogId, "2");
        } else {
            mPresenter.getLive(catalogId, "1");
        }


        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setEnableLoadMore(false);

        builder = new LoadingDialog.Builder(getActivity());
        builder.setCanceledOnTouchOutside(false);
        builder.setCancelable(true);


    }

    /**
     * 设置监听
     */
    private void setListeners() {
        //重置信息
        reset.setOnClickListener(view -> {
            reset();//重置
        });

        //提交
        commit.setOnClickListener(view -> {
            //提交检测
            checkInfo();
        });

        //扫码
        invoiceScan.setOnClickListener(view -> MPermissionUtils.requestPermissionsResult(LuckDrawFragment.this, 5, new String[]{Manifest.permission.CAMERA}, new MPermissionUtils.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {
                RouterManager.router(getActivity(), ARouterPathConstant.SCAN_CODE, SCAN_CODE);

            }

            @Override
            public void onPermissionDenied() {
                MPermissionUtils.showTipsDialog(getContext());
            }
        }));

        //日期选择
        invoiceDatetime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Calendar calendar = Calendar.getInstance();
                final DatePicker picker = new DatePicker(getActivity());
                picker.setCanceledOnTouchOutside(true);
                picker.setUseWeight(true);
                picker.setTopPadding(ConvertUtils.toPx(getContext(), 10));
                picker.setRangeEnd(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DATE));
                picker.setRangeStart(calendar.get(Calendar.YEAR) - 1, 1, 1);
                if (StringUtils.isEmpty(mYear)) {
                    picker.setSelectedItem(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DATE));
                } else {
                    picker.setSelectedItem(Integer.parseInt(mYear), Integer.parseInt(mMonth), Integer.parseInt(mDay));
                }
                picker.setResetWhileWheel(false);
                picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
                    @Override
                    public void onDatePicked(String year, String month, String day) {
                        mYear = year;
                        mMonth = month;
                        mDay = day;
                        invoiceDatetime.setText(Integer.parseInt(mYear) + "年" + Integer.parseInt(mMonth) + "月" + Integer.parseInt(mDay) + "日");
                    }
                });

                picker.setOnWheelListener(new DatePicker.OnWheelListener() {
                    @Override
                    public void onYearWheeled(int index, String year) {
                        picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay());
                    }

                    @Override
                    public void onMonthWheeled(int index, String month) {
                        picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay());
                    }

                    @Override
                    public void onDayWheeled(int index, String day) {
                        picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day);
                    }
                });
                picker.show();
            }
        });

        //中奖查询
        queryCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!StringUtils.isMobileNO(queryPhone.getText().toString())) {
                    Toasty.normal(getContext(), "请输入正确的手机号").show();
                    return;
                }
                builder.setTitle("查询中...");
                builder.show();
                mPresenter.queryInfo(queryPhone.getText().toString());
            }
        });

        //我的发票查询
        queryTicketsCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!StringUtils.isMobileNO(queryTicketsPhone.getText().toString())) {
                    Toasty.normal(getContext(), "请输入正确的手机号").show();
                    return;
                }
                builder.setTitle("查询中...");
                builder.show();
                mPresenter.queryTicketInfo(queryTicketsPhone.getText().toString());
            }
        });


        //跳转直播
        liveCover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.TELETEXTDETAIL);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    //预告

                    Bundle bundle = new Bundle();
                    bundle.putString("id", mBean.getId() + "");
                    RouterManager.router(ARouterPathConstant.TELE_VIDEO_ACTIVITY, bundle);
                } else {
                    Toasty.normal(getContext(), "此功能暂时不支持在当前手机系统版本上使用！").show();
                }
            }
        });

        //刷新
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                if (StringUtils.isNotEmpty(sections)) {
                    mPresenter.getTop(sections);
                }
                if (isHome) {
                    mPresenter.getLive(catalogId, "2");
                } else {
                    mPresenter.getLive(catalogId, "1");
                }
                mPresenter.getPhase();
            }
        });
        //轮播点击
        banner.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                NewsBean bean = bannerList.get(position);
                boolean hasPicture = StringUtils.isPictureSuccess(bean.getLogo());
                String type = "", pOne = "", pTwo = "", pThree = "";
                int style = 0;
                switch (bean.getType()) {
                    case "1"://普通新闻
                        type = "1";
                        switch (bean.getPluralPicsFlag()) {
                            case 0:
                                style = bean.getCommonStyle();
                                break;
                            case 1://三图
                                hasPicture = false;
                                if (bean.getImagess().size() == 1) {
                                    hasPicture = true;
                                    pOne = bean.getImagess().get(0).getImageUrlString();
                                } else if (bean.getImagess().size() == 2) {
                                    pOne = bean.getImagess().get(0).getImageUrlString();
                                    pTwo = bean.getImagess().get(1).getImageUrlString();
                                    hasPicture = true;
                                } else if (bean.getImagess().size() >= 3) {
                                    pOne = bean.getImagess().get(0).getImageUrlString();
                                    pTwo = bean.getImagess().get(1).getImageUrlString();
                                    pThree = bean.getImagess().get(2).getImageUrlString();
                                    hasPicture = true;
                                } else {
                                    hasPicture = false;
                                }
                                style = 4;
                                break;
                            case 2:
                                style = 3;
                                break;
                            default:
                                style = bean.getCommonStyle();
                                break;
                        }
                        break;
                    case "2"://图片新闻
                        type = "2";
                        if (bean.getImagess().size() == 1) {
                            pOne = bean.getImagess().get(0).getImageUrlString();
                            hasPicture = true;
                        } else if (bean.getImagess().size() == 2) {
                            pOne = bean.getImagess().get(0).getImageUrlString();
                            pTwo = bean.getImagess().get(1).getImageUrlString();
                            hasPicture = true;
                        } else if (bean.getImagess().size() >= 3) {
                            pOne = bean.getImagess().get(0).getImageUrlString();
                            pTwo = bean.getImagess().get(1).getImageUrlString();
                            pThree = bean.getImagess().get(2).getImageUrlString();
                            hasPicture = true;
                        } else {
                            hasPicture = false;
                        }
                        break;
                    case "3"://直播
                        type = "9";
                        break;
                    case "4"://标题新闻
                        type = "8";
                        break;
                    case "5"://视频新闻
                        type = "3";
                        style = bean.getVideoStyle();
                        break;
                    case "8"://互动直播
                        bean.setID(bean.getRoomId());//将roomId设置成通用Id
                        type = "5";
                        break;
                    case "101"://抓取新闻
                        type = "10";
                        break;
                    default:
                        break;
                }
                GlobalNewsBean globalNewsBean = new GlobalNewsBean(bean.getTitle(), bean.getID(), bean.getRedirectURL(), bean.getLogo(), style, bean.getPublishDate(), type, Integer.parseInt(bean.getHitCount()), bean.getSource(), bean.getCatalogID(), hasPicture, pOne, pTwo, pThree, bean.getLivetype());
                ItemSkipUtils.getInstance().itemSkip(globalNewsBean, getContext());
            }
        });

        complain.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putString("title", "发票投诉");
            bundle.putString("url", CommonUtils.getInstance().getComplainUrl());

        });


    }

    /**
     * 设置轮播
     *
     * @param isShow
     * @param beanList
     */
    @Override
    public void setTop(boolean isShow, List<NewsBean> beanList) {
        refresh.finishRefresh();
        if (isShow) {
            banner.setVisibility(View.VISIBLE);
            dividerLine.setVisibility(View.VISIBLE);

            bannerList = new ArrayList<>();
            bannerList.addAll(beanList);

            List<String> titleNames = new ArrayList<>();
            for (int i = 0; i < bannerList.size(); i++) {
                titleNames.add(bannerList.get(i).getTitle());
            }
            String[] titleStrings = new String[titleNames.size()];
            titleNames.toArray(titleStrings);
            //当只有一张轮播图时
            if (bannerList.size() == 1) {
                banner.setTextBanner(titleStrings[0]);
                banner.setCanLoop(false);//停止轮播
            }
            banner.setPages(new SimpleHolderCreator() {
                @Override
                public Object createHolder() {
                    return new BannerImageHolderView();
                }
            }, bannerList)
                    .startTurning(3000)//轮播3s一次
                    .setPageIndicator(new int[]{R.drawable.news_banner_indicator_off, R.drawable.news_banner_indicator_on}, titleStrings)
                    .setPageIndicatorAlign(SimpleBannerView.PageIndicatorAlign.ALIGN_PARENT_RIGHT);

        } else {
            banner.setVisibility(View.GONE);
            dividerLine.setVisibility(View.GONE);
        }
    }

    /**
     * 设置直播
     *
     * @param isShow
     * @param beanList
     */
    @Override
    public void setLive(boolean isShow, List<LuckDrawLiveBean> beanList) {
        refresh.finishRefresh();
        if (isShow) {
            luckdrawLiveLayout.setVisibility(View.VISIBLE);
            mBean = beanList.get(0).getMenuLive();
            //设置标题
            liveTitle.setText(mBean.getTitle());
            //设置封面图
            Glide.with(getContext().getApplicationContext())
                    .load(mBean.getCoverPic())
                    .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default).transform(new GlideRoundTransform(4)))
                    .into(liveCover);

            //状态
            int status = Integer.parseInt(StringUtils.isEmpty(mBean.getStatus()) ? "0" : mBean.getStatus());
            switch (status) {
                case 6:
                    //预告
                    liveTag.setText("预告");
                    break;
                case 7:
                    //回放
                    liveTag.setText("回顾");
                    break;
                case 2:
                    //直播
                    liveTag.setText("直播");
                    break;
                case 3:
                    //结束
                    liveTag.setText("结束");
                    break;
                default:
                    liveTag.setText("未知");
                    break;
            }

            //浏览数
            try {
                int minPlay = Integer.parseInt(CommonUtils.getInstance().getMinPlay());
                if (minPlay == 0) {
                    scanNum.setVisibility(View.GONE);
                } else {
                    //判断评论数是否大于最少浏览数
                    if (StringUtils.isEmpty(mBean.getHits())) {
                        scanNum.setVisibility(View.GONE);
                    } else if (Integer.parseInt(mBean.getHits()) >=
                            minPlay) {
                        scanNum.setText(StringUtils.transformNum(mBean.getHits() + "") + " 关注");
                        scanNum.setVisibility(View.VISIBLE);
                    } else {
                        scanNum.setVisibility(View.GONE);
                    }
                }

            } catch (Exception e) {
                scanNum.setVisibility(View.GONE);
            }
        } else {
            luckdrawLiveLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 检查提交信息是否完整
     */
    private void checkInfo() {
        if (StringUtils.isEmpty(invoiceCode.getText().toString())) {
            Toasty.normal(getContext(), "请填写发票代码！").show();
            return;
        }

        if (StringUtils.isEmpty(invoiceNum.getText().toString())) {
            Toasty.normal(getContext(), "请填写发票号码！").show();
            return;
        }

        if (StringUtils.isEmpty(invoiceSum.getText().toString())) {
            Toasty.normal(getContext(), "请填写发票金额！").show();
            return;
        } else if (Double.parseDouble(invoiceSum.getText().toString()) < moneyLimit) {
            Toasty.normal(getContext(), "发票金额不得低于" + moneyLimit + "元！").show();
            return;
        }

        if (StringUtils.isEmpty(invoiceBusiness.getText().toString()) && CommonUtils.getInstance().getSite() == 181) {
            Toasty.normal(getContext(), "请填写开票商家！").show();
            return;
        }


        if (StringUtils.isEmpty(invoiceDatetime.getText().toString())) {
            Toasty.normal(getContext(), "请填写发票日期！").show();
            return;
        }

        if (!StringUtils.isMobileNO(invoicePhone.getText().toString())) {
            Toasty.normal(getContext(), "请输入正确的手机号").show();
            return;
        }
        builder.setTitle("提交中...");
        builder.show();
        mPresenter.commitInfo(invoiceCode.getText().toString(), invoiceNum.getText().toString(), invoiceSum.getText().toString()
                , invoiceDatetime.getText().toString(), invoicePhone.getText().toString(), invoiceBusiness.getText().toString());
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right,
                               int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) { //软键盘弹起
            if (isHome && homeActivityInterface != null) {
                homeActivityInterface.setTabbarVisibility();
            }
        } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) { //软键盘关闭

        }
    }


    /**
     * 顶部轮播holder
     */
    class BannerImageHolderView implements SimpleHolder<NewsBean> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, NewsBean data) {
            Glide.with(context.getApplicationContext())
                    .load(data.getLogo())
                    .apply(new RequestOptions()
                            .centerCrop()
                            .placeholder(R.drawable.cover_large_default)
                            .error(R.drawable.cover_large_default))
                    .into(imageView);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 5) {
            RouterManager.router(getActivity(), ARouterPathConstant.SCAN_CODE, SCAN_CODE);

        } else {
            Toasty.normal(getContext(), "您没有相机权限，请在手机设置中授权！", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == SCAN_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    if (StringUtils.isNotEmpty(result)) {
                        String[] results = result.split(",");
                        try {
                            invoiceCode.setText(results[2]);
                            invoiceNum.setText(results[3]);
                            if (StringUtils.isNotEmpty(results[4])) {
                                invoiceSum.setText(results[4]);
                            }
                            if (StringUtils.isNotEmpty(results[5])) {
                                mYear = results[5].substring(0, 4);
                                mMonth = results[5].substring(4, 6);
                                mDay = results[5].substring(6, 8);
                                invoiceDatetime.setText(Integer.parseInt(mYear) + "年" + Integer.parseInt(mMonth) + "月" + Integer.parseInt(mDay) + "日");
                            }
                        } catch (Exception e) {
                            Toasty.normal(getContext(), "请检查二维码是否无效或非发票类型！").show();
                        }
                    }
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toasty.normal(getContext(), "解析二维码失败").show();
                }
            }
        }
    }

    @Override
    public void setPhase(LuckDrawPhaseBean bean) {
        invoiceLayout.setVisibility(View.VISIBLE);
        invocieEmptyTv.setVisibility(View.GONE);
        if (StringUtils.isNotEmpty(bean.getName())) {
            phase.setText(bean.getName());
        } else {
            phase.setText("暂无活动");
        }
        moneyLimit = bean.getAmountLow();
    }

    @Override
    public void setPhaseError(String msg) {
        invoiceLayout.setVisibility(View.GONE);
        invocieEmptyTv.setVisibility(View.VISIBLE);
    }


    /**
     * 查询成功
     *
     * @param isWinner 是否中奖
     * @param beanList 中奖信息
     */
    @Override
    public void setQueryInfoSuccess(boolean isWinner, final List<LuckDrawInfoBean> beanList) {
        if (builder != null) {
            builder.dismiss();
        }

        if (isWinner) {
            new OtherDialog.Builder(getContext())
                    .setContentView(R.layout.news_dialog_luck_draw_success)
                    .setOnClickListener(R.id.to_detail, view -> {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("list", (Serializable) beanList);
                        bundle.putString("phone", queryPhone.getText().toString());
                        RouterManager.router(ARouterPathConstant.LUCK_DRAW_WINNER, bundle);

                    }).show();
        } else {
            new OtherDialog.Builder(getContext())
                    .setContentView(R.layout.news_dialog_luck_draw_fail)
                    .setDismissButton(R.id.cancel)
                    .show();
        }
    }

    /**
     * 查询失败
     *
     * @param msg
     */
    @Override
    public void setQueryInfoError(String msg) {
        if (builder != null) {
            builder.dismiss();
        }
        Toasty.normal(getContext(), msg).show();
    }

    @Override
    public void queryTicketInfoSuccess(List<LuckDrawInfoBean> beanList) {
        if (builder != null) {
            builder.dismiss();
        }

        if (beanList != null) {
            Bundle bundle = new Bundle();
            bundle.putSerializable("list", (Serializable) beanList);
            bundle.putString("phone", queryTicketsPhone.getText().toString());
            RouterManager.router(ARouterPathConstant.LUCK_DRAW_TICKETS, bundle);

        } else {
            Toasty.normal(getContext(), "暂无发票信息！").show();
        }
    }

    @Override
    public void queryTicketInfoError(String msg) {
        if (builder != null) {
            builder.dismiss();
        }
        Toasty.normal(getContext(), msg).show();
    }

    /**
     * 重置
     */
    private void reset() {
        invoiceCode.setText("");
        invoiceNum.setText("");
        invoiceSum.setText("");
        invoicePhone.setText("");
        invoiceDatetime.setText("");
        invoiceBusiness.setText("");
        mYear = "";
    }

    /**
     * 提交返回结果
     *
     * @param isSuccess
     * @param msg
     */
    @Override
    public void commentResult(boolean isSuccess, String msg) {
        if (builder != null) {
            builder.dismiss();
        }
        Toasty.normal(getContext(), msg).show();
        if (isSuccess) {
            reset();
        }
    }
}